﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace UI
{
    public class CookTab : MonoBehaviour
    {
        public UIScrollView scrollView;
        public SimpleGrid simpleGrid;
        public ArrayPage arrayPage;
        public GameObject emptyPrefab;

        string lastChosedId = "";
        Dictionary<string, FishIcon> dishIcons = new Dictionary<string, FishIcon>();

        public void UpdateScrollView()
        {
            foreach (var item in simpleGrid.childs)
            {
                Destroy(item);
            }
            simpleGrid.childs.Clear();
            dishIcons.Clear();

            GameObject obj = AssetLoad.ResourceManager.Instance.LoadResource("prefab/FishIcon") as GameObject;
            int count = 0;
            List<UIFishItem> list = StaticData.playerData.GetDishItemsOrderByStar();
            foreach(var fish in list)
            {
                GameObject icon = Instantiate(obj);
                Destroy(icon.GetComponent<BoxCollider>());
                simpleGrid.AddChild(icon);
                FishIcon fishicon = icon.GetComponent<FishIcon>();
                fishicon.UpdateCount(fish.num.ToString(), UIWidget.Pivot.Right);
                fishicon.SetFish(fish.fishData.FishItemID);
                fishicon.m_callback = OnFishIconClick;
                icon.transform.localScale = new Vector3(0.9f, 0.9f, 0.9f);
                icon.SetActive(true);
                count++;
                dishIcons[fish.fishData.FishItemID] = fishicon;
            }

            int pagecount = 20;
            if (count > pagecount && count % 4 != 0)
                pagecount = count + 4 - count % 4;
           
            for (int i = count; i < pagecount; i++)
            {
                GameObject icon = Instantiate(emptyPrefab);
                Destroy(icon.GetComponent<BoxCollider>());
                simpleGrid.AddChild(icon);
                icon.transform.localScale = new Vector3(0.9f, 0.9f, 0.9f);
                icon.SetActive(true);
            }

            scrollView.ResetPosition();
        }

        void OnFishIconClick(string id)
        {
            if (dishIcons.ContainsKey(lastChosedId))
                dishIcons[lastChosedId].chosedImg.SetActive(false);
            dishIcons[id].chosedImg.SetActive(true);

            lastChosedId = id;

            PageManager.instance.OpenPage("EnjoyCookingPage","id=" + id + "&pos=" + arrayPage.CurPosition.ToString());
        }
    }
}

